package edu.osu.cse551;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Launcher extends Activity implements OnClickListener {
	// Contact Selection
	private AlertDialog alert;
	private Button mBtnContacts;
	private Button msgBtn;
	private String contact;
	private TextView emgMsg;
	private static CharSequence message;
	private TextView selectedContact;
	private final int PICK = 1;
	// Store contact data here
	private String FILENAME = "contact_file";
	private String MESSAGEFILE = "message_file";
	private String PHONENOFILE = "phone_number";
	private static String phone;

	private String TAG = "ContactsDemo";

	// Shake Detection

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get contact from local file
		initializeContact();
		initializeMessage();
		initializePhone();
		setContentView(R.layout.main);

		// Display Contact value on Preferences menu
		selectedContact = (TextView) findViewById(R.id.textview);
		selectedContact.setText(contact);

		emgMsg = (TextView) findViewById(R.id.textView1);
		emgMsg.setText(message);

		// Set up Select Contact Button
		mBtnContacts = (Button) findViewById(R.id.xBtnContacts);
		mBtnContacts.setOnClickListener(this);
		msgBtn = (Button) findViewById(R.id.button1);
		msgBtn.setOnClickListener(this);

		startService(new Intent(ShakeDetection.class.getName()));

	}

	// Either get the contact from file or initialize it
	private void initializeContact() {
		FileInputStream in = null;
		BufferedInputStream buf = null;
		try {
			in = openFileInput(FILENAME);
			buf = new BufferedInputStream(in);

		} catch (FileNotFoundException e1) {
			// File doesn't exist yet, first run
			contact = "No Contact Selected";
			return;
		}

		// Read from input stream
		byte[] buffer = new byte[256];
		try {
			int res = buf.read(buffer, 0, 256);
			if (res == -1) {
				// File was empty
				contact = "No Contact Selected";
			} else {
				contact = new String(buffer);
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			contact = "No Contact Selected";
		}
	}

	private void initializeMessage() {
		
		FileInputStream in = null;
		BufferedInputStream buf = null;
		try {
			in = openFileInput(MESSAGEFILE);
			buf = new BufferedInputStream(in);
		} catch (FileNotFoundException e) {
			message = "<No message>";
			return;
		}

		// read from file
		byte[] buffer = new byte[256];
		try {
			int res = buf.read(buffer, 0, 250);
			if (res == -1) {
				// file was empty
				message = "<No message>";
			} else {
				message = new String(buffer);
			}
			in.close();
		} catch (IOException e1) {
			e1.printStackTrace();
			message = "<No message>";
		}
		
		//message = ShakeDetection.getMessage();
	}

	private void initializePhone() {
		
		FileInputStream in = null;
		BufferedInputStream buf = null;
		try {
			in = openFileInput(PHONENOFILE);
			buf = new BufferedInputStream(in);

		} catch (FileNotFoundException e1) {
			// File doesn't exist yet, first run
			phone = "0";
			return;
		}

		// Read from input stream
		byte[] buffer = new byte[256];
		try {
			int res = buf.read(buffer, 0, 256);
			if (res == -1) {
				// File was empty
				phone = "0";
			} else {
				phone = new String(buffer);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			phone = "0";
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.xBtnContacts:
			Intent intent = new Intent(Intent.ACTION_PICK,
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
			startActivityForResult(intent, PICK);
			break;
		case R.id.button1:
			// Opening Message Input Window as a Window
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Emergency Message");

			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			builder.setView(input);

			builder.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							CharSequence newMessage = input.getText();
							//message = input.getText();
							if (newMessage.length() > 160) {
								Toast.makeText(getBaseContext(), 
										"Message must be shorter than 160 characters.", Toast.LENGTH_SHORT).show();
							} else {
								message = newMessage;
								emgMsg.setText(message);
								writeMessage();
							}
						}
					});

			builder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// Canceled.
						}
					});

			alert = builder.create();
			alert.show();
			break;
		}

	}

	// This code grabs the contact name and sets the contact variable
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (PICK):
			if (resultCode == Activity.RESULT_OK) {
				Uri result = data.getData();
				Log.v(TAG, "Got a result: " + result.toString());

				// get the phone number id from the Uri
				String id = result.getLastPathSegment();

				// query the phone numbers for the selected phone number id
				Cursor c = getContentResolver().query(Phone.CONTENT_URI, null,
						Phone._ID + "=?", new String[] { id }, null);

				int phoneIdx = c.getColumnIndex(Phone.NUMBER);
				int contactIdx = c.getColumnIndex(Phone.DISPLAY_NAME);

				if (c.getCount() == 1) { // contact has a single phone number
					// get the only phone number
					if (c.moveToFirst()) {
						phone = c.getString(phoneIdx);
						writePhone();
						contact = c.getString(contactIdx);
						selectedContact.setText(contact);
						writeContact();

						Log.v(TAG, "Got phone number: " + phone);

					} else {
						Log.w(TAG, "No results");
					}
				}

			}

			break;
		}
	}

	// Run in Background
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	//The following methods store updated contact details into file system
	private void writePhone() {
		FileOutputStream fos;

		try {
			fos = openFileOutput(PHONENOFILE, Context.MODE_WORLD_READABLE);
			fos.write(phone.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void writeMessage() {
		FileOutputStream fos;

		try {
			fos = openFileOutput(MESSAGEFILE, Context.MODE_WORLD_READABLE);
			fos.write(message.toString().getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void writeContact() {
		FileOutputStream fos;
		
		try {
			fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
			fos.write(contact.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}